package com.soyoung.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;

import java.io.Serializable;
import java.util.*;

/**
 * @Author : zhq
 * @since : 2018/5/9
 */
public class JsonUtils implements Serializable{

    /**
     * 解析json object返回一个map
     * key : null 只是个jsonobject 对象
     * key : 非空.. json里面嵌套json对象
     */
    public static Map<?,?> parseJsonObjectToMap(String jsonStr,String key){
        Map<?,?> map = new HashMap<>();
        if (StringUtils.isNotBlank(key)){
            JSONObject obj =  JSONObject.parseObject(jsonStr);
            String str =null!=obj.get(key)?obj.get(key).toString():null;
            if (StringUtils.isNotBlank(str)){
                map = (Map)JSONObject.parseObject(str);
            }
        }else {
            map =  JSONObject.parseObject(jsonStr);
        }
        return map;
    }

    /**
     * 解析json Array返回一个list
     */
    public static List<?> parseJsonArrayToList(String jsonArray, String key){
        List<Object> list = new ArrayList<>();
        JSONObject jso=JSON.parseObject(jsonArray);//json字符串转换成jsonobject对象
        JSONArray jsarr=jso.getJSONArray(key);//jsonobject对象取得data对应的jsonarray数组
        for (int i=0;i<jsarr.size();i++){
            Object obj = jsarr.get(i);
            list.add(obj);

        }
        return  list;
    }


    /**
     * main 测试
     * @param args
     */
    public static void main(String[] args) {
        String key = "data";
        String JSON_SIMPLE ="{\n" +
                "    \"code\": \"10000\",\n" +
                "    \"desc\": \"请求成功\",\n" +
                "    \"data\": {\n" +
                "        \"sumLoanMoneys\": 0,\n" +
                "        \"sumRealUnameCount\": 129,\n" +
                "        \"sumOrderSuccess\": 0,\n" +
                "        \"sumHasQuotaTotalCount\": 11,\n" +
                "        \"sumCreditQuota\": 4700000,\n" +
                "        \"sumHasRake\": \"0.00\"\n" +
                "    }\n" +
                "}";
        Map map = parseJsonObjectToMap(JSON_SIMPLE,key);
        System.out.println(map.toString());

        String jsonArray="{\"name\":\"张三\",\"age\":15,\"data\":[{\"key1\":\"value1\",\"key2\":\"value2\"},{\"key3\":\"value3\",\"key4\":\"value4\"}]}";
        List list = parseJsonArrayToList(jsonArray,key);
        System.out.println(list.toString());
        List<Map> l = list;
        l.forEach(maps->{
            maps.forEach((k,v)->{
                System.out.println(k+":"+v);
            });
        });
    }
}
